package com.leo.springbootmultithreadbasic.lock.reentranreadwritelock.readwrite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Leo
 * @version V1.0
 * @date 2021/11/5 10:25 PM
 */
public class MyService {

    private Logger logger = LoggerFactory.getLogger(MyService.class);

    // build ReentrantReadWriteLock
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void read() {
        try {
            // get read lock
            readWriteLock.readLock().lock();

            // log
            logger.info("Get read lock: {}, time={}", Thread.currentThread().getName(), System.currentTimeMillis());
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void write() {
        try {
            // get read lock
            readWriteLock.writeLock().lock();

            // log
            logger.info("Get write  lock: {}, time={}", Thread.currentThread().getName(), System.currentTimeMillis());
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}
